package com.huanghuai.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Response;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if(!requestURI.equals("/login/doLogin")){
            doFilter(request,response,filterChain);//不是登录请求直接放行
            return;
        }
        //校验验证码
        validateCode(request,response,filterChain);

    }

    private void validateCode(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //从前端获取验证码
        String code = request.getParameter("code");
        //从Session中获取验证码
        String captcha = (String)request.getSession().getAttribute("CAPTCHA");
        request.getSession().removeAttribute("captcha_code_error");//清除错误信息
        //判断二者是否相等
        if(StringUtils.isEmpty(code)){
            request.getSession().setAttribute("captcha_code_error","请输入验证码");
            response.sendRedirect("/toLogin");
            return;
        }
        if(StringUtils.isEmpty(captcha)){
            request.getSession().setAttribute("captcha_code_error","验证码错误");
            response.sendRedirect("/toLogin");
            return;
        }
        if(!code.equalsIgnoreCase(captcha)){
            request.getSession().setAttribute("captcha_code_error","验证码输入错误");
            response.sendRedirect("/toLogin");
            return;
        }
        request.getSession().removeAttribute("captcha_code_error");//删除session中的验证码
        this.doFilter(request,response,filterChain);
    }
}
